from sqlalchemy.orm import Session
from typing import Optional, List
from datetime import datetime

from src.database.manager import DBManager
from src.database.models import VideoGenerationConfig
from src.utils.logger import log_info, log_error

class VideoGenerationConfigDAO:
    """Data Access Object for VideoGenerationConfig model."""
    
    def __init__(self, session: Session = DBManager().get_session()):
        self.session = session
        
    def create(self, name: str = None, prompt_data: list = None, date_range: dict = None,
               transition_effect: str = None, transition_duration: float = None,
               remove_voice: bool = False, random_limit: int = None,
               generate_all: bool = False, created_by: str = None) -> VideoGenerationConfig:
        """Create a new video generation configuration."""
        try:
            config = VideoGenerationConfig(
                name=name,
                prompt_data=prompt_data,
                date_range=date_range,
                transition_effect=transition_effect,
                transition_duration=transition_duration,
                remove_voice=remove_voice,
                random_limit=random_limit,
                generate_all=generate_all,
                created_by=created_by,
                created_at=datetime.now()
            )
            
            self.session.add(config)
            self.session.commit()
            log_info(f"Created video generation config with ID: {config.id}")
            return config
        except Exception as e:
            self.session.rollback()
            log_error(f"Error creating video generation config: {e}")
            raise
    
    def get_by_id(self, config_id: int) -> Optional[VideoGenerationConfig]:
        """Get configuration by ID."""
        return self.session.query(VideoGenerationConfig).filter(VideoGenerationConfig.id == config_id).first()
    
    def get_all(self, limit: int = 100, offset: int = 0) -> List[VideoGenerationConfig]:
        """Get all configurations with pagination."""
        return self.session.query(VideoGenerationConfig)\
            .order_by(VideoGenerationConfig.created_at.desc())\
            .limit(limit).offset(offset).all()
    
    def delete(self, config_id: int) -> bool:
        """Delete a configuration by ID."""
        config = self.get_by_id(config_id)
        if not config:
            return False
            
        self.session.delete(config)
        self.session.commit()
        return True


